/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.uff.pgci.sgca.gateway.codec;

import br.uff.pgci.sgca.gateway.model.Mensagem;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.serialization.CompatibleObjectEncoder;
import org.jboss.netty.util.CharsetUtil;

/**
 *
 * @author anapaula
 */
public class MensagemEncoder extends CompatibleObjectEncoder {

    protected Object encode(ChannelHandlerContext chc, Channel chnl, Object obj) throws Exception {
        System.out.println("xxxxxxxxxxxxxxxxx");
        if (!(obj instanceof Mensagem)) {
            throw new Exception("Objeto invalido. Esperava Mensagem, recebeu:" + obj.getClass());
        }

        Mensagem m = (Mensagem) obj;

        System.out.println("vai retornar!");

        ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
        buf.writeBytes(("X" + m.getIdComando() + "Y").getBytes(CharsetUtil.ISO_8859_1));
        System.out.println("Retornando...");
        return buf;

        // Convert the number into a byte array.
//        byte[] data = v.toByteArray();
//        int dataLength = data.length;
//
//        // Construct a message.
//        ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
//        buf.writeByte((byte) 'F'); // magic number
//        buf.writeInt(dataLength);  // data length
//        buf.writeBytes(data);      // data
    }
}
